package org.jd.export.service;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder.Enum;
import lombok.RequiredArgsConstructor;
import org.jd.export.model.ColumnInfo;
import org.jd.export.model.TableInfo;
import org.jd.export.repo.SchemaRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SchemaService {

    private final SchemaRepository schemaRepository;
    
    @Value("${export.word.output-path:src/main/resources/database_schema.docx}")
    private String defaultOutputPath;

    /**
     * 获取指定数据库中所有表的完整结构信息
     */
    public List<TableInfo> getAllTablesInSchema(String databaseName) {
        return schemaRepository.getAllTables(databaseName);
    }

    /**
     * 使用默认路径导出数据库结构到Word文档
     */
    public void exportDbToWord(List<TableInfo> tableList) {
        exportDbToWord(tableList, defaultOutputPath);
    }
    
    /**
     * 导出数据库结构到Word文档
     */
    public void exportDbToWord(List<TableInfo> tableList, String outputPath){
        try (XWPFDocument document = new XWPFDocument()) {
            
            // 添加标题
            XWPFParagraph titlePara = document.createParagraph();
            titlePara.setAlignment(ParagraphAlignment.CENTER);
            titlePara.setSpacingAfter(500); // 增加段后间距
            XWPFRun titleRun = titlePara.createRun();
            titleRun.setText("数据库结构文档");
            titleRun.setBold(true);
            titleRun.setFontSize(26);
            titleRun.setFontFamily("微软雅黑");
            titleRun.setColor("333333"); // 深灰色标题

            // 添加空行
            document.createParagraph();
            
            // 循环处理每个表
            for (TableInfo table : tableList) {
                // 添加表名
                XWPFParagraph tableNamePara = document.createParagraph();
                tableNamePara.setSpacingBefore(150); // 表前间距
                tableNamePara.setSpacingAfter(80);   // 表后间距
                XWPFRun tableNameRun = tableNamePara.createRun();
                tableNameRun.setText(table.getTableName());
                tableNameRun.setBold(true);
                tableNameRun.setFontSize(18);
                tableNameRun.setFontFamily("微软雅黑");
                tableNameRun.setColor("333333"); // 深灰色表名

                // 添加表描述
                if (table.getTableComment() != null && !table.getTableComment().trim().isEmpty()) {
                    XWPFParagraph commentPara = document.createParagraph();
                    commentPara.setSpacingAfter(100); // 描述后间距
                    XWPFRun commentRun = commentPara.createRun();
                    commentRun.setText(table.getTableComment());
                    commentRun.setFontSize(12);
                    commentRun.setFontFamily("微软雅黑");
                    commentRun.setColor("666666"); // 中灰色描述文字
                    // 简洁显示描述
                }
                
                // 创建字段表格
                XWPFTable tableDoc = document.createTable(table.getColumnInfos().size() + 1, 3);
                
                // 设置表格样式
                tableDoc.setWidth("100%");
                tableDoc.setTableAlignment(TableRowAlign.CENTER);
                
                // 设置表格边框 - 简洁边框样式
                tableDoc.setTopBorder(XWPFBorderType.SINGLE, 4, 0, "CCCCCC");      // 顶部边框：浅灰色，4pt
                tableDoc.setBottomBorder(XWPFBorderType.SINGLE, 4, 0, "CCCCCC");   // 底部边框：浅灰色，4pt
                tableDoc.setLeftBorder(XWPFBorderType.SINGLE, 4, 0, "CCCCCC");     // 左边框：浅灰色，4pt
                tableDoc.setRightBorder(XWPFBorderType.SINGLE, 4, 0, "CCCCCC");    // 右边框：浅灰色，4pt
                tableDoc.setInsideHBorder(XWPFBorderType.SINGLE, 1, 0, "E0E0E0");  // 内部水平边框：更浅灰色，1pt
                tableDoc.setInsideVBorder(XWPFBorderType.SINGLE, 1, 0, "E0E0E0");  // 内部垂直边框：更浅灰色，1pt
                
                // 设置列宽比例 (字段名:字段类型:字段说明 = 3:3:6) - 更合理的比例
                tableDoc.getCTTbl().addNewTblGrid();
                tableDoc.getCTTbl().getTblGrid().addNewGridCol().setW(java.math.BigInteger.valueOf(2500)); // 字段名
                tableDoc.getCTTbl().getTblGrid().addNewGridCol().setW(java.math.BigInteger.valueOf(2500)); // 字段类型
                tableDoc.getCTTbl().getTblGrid().addNewGridCol().setW(java.math.BigInteger.valueOf(5000)); // 字段说明
                
                // 添加表头
                XWPFTableRow headerRow = tableDoc.getRow(0);
                headerRow.getCell(0).setText("字段名");
                headerRow.getCell(1).setText("字段类型");
                headerRow.getCell(2).setText("字段说明");
                
                // 设置表头样式
                for (int i = 0; i < 3; i++) {
                    XWPFTableCell cell = headerRow.getCell(i);
                    // 设置表头背景色为浅灰色
                    cell.setColor("F5F5F5");
                    // 设置单元格内边距
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                    
                    XWPFParagraph para = cell.getParagraphs().get(0);
                    para.setAlignment(ParagraphAlignment.CENTER);
                    para.setSpacingBefore(120); // 上边距
                    para.setSpacingAfter(120);  // 下边距
                    para.setIndentationLeft(100);  // 左内边距
                    para.setIndentationRight(100); // 右内边距
                    
                    XWPFRun run = para.createRun();
                    run.setBold(true);
                    run.setFontSize(13);
                    run.setFontFamily("微软雅黑");
                    run.setColor("333333"); // 深灰色文字
                }
                
                // 添加字段数据
                for (int i = 0; i < table.getColumnInfos().size(); i++) {
                    ColumnInfo column = table.getColumnInfos().get(i);
                    XWPFTableRow dataRow = tableDoc.getRow(i + 1);
                    
                    dataRow.getCell(0).setText(column.getColumnName());
                    dataRow.getCell(1).setText(column.getColumnType());
                    dataRow.getCell(2).setText(column.getColumnComment() != null ? column.getColumnComment() : "");
                    
                    // 设置数据行样式
                    for (int j = 0; j < 3; j++) {
                        XWPFTableCell cell = dataRow.getCell(j);
                        // 交替行背景色 - 简洁配色
                        if (i % 2 == 0) {
                            cell.setColor("FAFAFA"); // 非常浅的灰色
                        } else {
                            cell.setColor("FFFFFF"); // 纯白色
                        }
                        // 设置单元格垂直对齐
                        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                        
                        XWPFParagraph para = cell.getParagraphs().get(0);
                        para.setAlignment(ParagraphAlignment.CENTER);
                        para.setSpacingBefore(100);  // 上边距
                        para.setSpacingAfter(100);   // 下边距
                        para.setIndentationLeft(80);   // 左内边距
                        para.setIndentationRight(80);  // 右内边距
                        
                        XWPFRun run = para.createRun();
                        run.setFontSize(11);
                        run.setFontFamily("微软雅黑");
                        run.setColor("333333"); // 深灰色文字
                    }
                }

                // 表格后添加适当间距
                XWPFParagraph afterTablePara = document.createParagraph();
                afterTablePara.setSpacingAfter(300);
            }
            
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(outputPath)) {
                document.write(out);
            }
            
            System.out.println("数据库结构文档生成成功：" + outputPath);
            
        } catch (Exception e) {
            System.err.println("导出Word文档失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
